Ext.define('CA.base.UploadPanel', {
    extend: 'Ext.grid.Panel',
    xtype: 'CA.base.UploadPanel',

    uses: [
        'Ext.ux.grid.column.ProgressBar',

        'CA.base.File'
    ],

    urlFilter: '',
    cls: 'c-no-dirty',

    initComponent: function(){
        var config = {
            store: this.buildStore(),
            viewConfig: {
                markDirty: false
            },
            tbar: [
                {
                    text: 'Выбрать файлы',
                    iconCls: 'c-icon-attach',
                    itemId: 'pickFiles'
                },
                {
                    text: 'Загрузить',
                    iconCls: 'c-icon-upload',
                    handler: this.doUploadFiles,
                    itemId: 'btnUpload',
                    disabled: true,
                    scope: this
                },
                '->',
                {
                    text: 'Очистить',
                    handler: this.doClearFiles,
                    itemId: 'btnClear',
                    disabled: true,
                    scope: this
                }
            ],
            columns: {
                defaults: {
                    hideable: false
                },
                items: [
                    {
                        header: 'Имя',
                        flex: 1,
                        dataIndex: 'name'
                    },
                    {
                        header: 'Размер',
                        width: 70,
                        dataIndex: 'size'
                    },
                    {
                        header: 'Состояние',
                        width: 70,
                        renderer: this.percentRenderer,
                        dataIndex:'percent'
                    },
                    {
                        xtype:'actioncolumn',
                        width: 24,
                        sortable: false,
                        resizable: false,
                        items: [
                            {
                                icon: CA.content('icons/16/cancel.png'),
                                tooltip: 'Удалить',
                                scope: this,
                                handler: function(grid, rowIndex) {
                                    this.getStore().removeAt(rowIndex);
                                }
                            }
                        ]
                    }
                ]
            }
        };

        Ext.apply(this, config);

        this.on('afterrender', this.onAfterRender, this);
        this.callParent();
    },

    percentRenderer: function(val, meta){
        var cls = '',
            w = val;

        switch(val){
            case -1:
                cls = 'empty';
                val = 'Ожидание';
                w = 0;
                break;
            case -2:
                cls = 'error';
                val = 'Ошибка';
                w = 100;
                break;
            case 100:
                cls = 'complete';
                w = 100;
                val = 'Загружен';
                break;

            default:
                val += '%';
                break;
        }

        meta.style = 'padding: 1px';

        return '<div class="c-pb-cell ' + cls + '">' +
            '<span style="width:' + w + '%"></span>' +
            '<div>' + val + '</div>' +
            '</div>';
    },

    onAfterRender: function(){
        var btn = this.down('#pickFiles');

        var uploader = new plupload.Uploader({
            runtimes : 'gears,html5,flash,silverlight,browserplus',
            browse_button : btn.id,
            container : this.id,
            max_file_size : '10mb',
            url : CA.url('/files/upload/' + this.urlFilter),
            flash_swf_url : CA.url('res/plupload/plupload.flash.swf'),
            silverlight_xap_url : CA.url('res/plupload/plupload.silverlight.xap'),
            filters : [
                { title : "Image files", extensions : "jpg,gif,png" }
            ],
            resize : {width : 800, height : 600, quality : 90}
        });

        uploader.bind('FilesAdded', this.onFilesSelect, this);
        uploader.bind('UploadProgress', this.onUploadProgress, this);
        uploader.bind('FileUploaded', this.onFileUploaded, this);
        uploader.bind('Error', this.onUploaderError, this);

        uploader.init();

        this.uploader = uploader;
    },

    onUploadProgress: function(up, file){
        var rec = this.getStore().getById(file.id);

        if(rec && rec.data.percent != -2){
            rec.set('percent', file.percent);
        }
    },

    onFileUploaded: function(up, file, resp){
        var data = Ext.decode(resp.response),
            store = this.getStore(),
            rec = store.getById(file.id);

        up.removeFile(file);
        this.checkActions();

        if(up.files.length == 0)
            this.fireEvent('filesUploaded');

        if(rec){
            rec.set('percent', data.success ? 100 : -2);
        }
    },

    onUploaderError: function(up, err){
        if(err.file){
            var record = this.getStore().getById(err.file.id);

            up.removeFile(err.file);
            this.checkActions();

            if(record){
                record.set('percent', -2);
            }
        }
    },

    onFilesSelect: function(up, files){
        Ext.each(files, function(file){
            var rec = this.getStore().add(file)[0];
            rec.set('percent', -1);
            rec.file = file;
        }, this);

        this.checkActions(files);
        up.refresh();
    },

    buildStore: function(){
        return {
            xtype: 'store',
            model: 'CA.base.File',
            listeners: {
                scope: this,
                remove: this.onStoreRemove
            }
        };
    },

    onStoreRemove: function(store, rec){
        this.uploader.removeFile(rec.file);
        this.checkActions();
    },

    checkActions: function(files){
        var store = this.getStore(),
            count = store.count(),
            btnClear = this.down('#btnClear'),
            btnUpload = this.down('#btnUpload');
        files = files || this.uploader.files;

        btnClear.setDisabled(!count);
        btnUpload.setDisabled(!files.length);
    },

    doUploadFiles: function(){
        this.uploader.start();
    },

    doClearFiles: function(){
        var up = this.uploader,
            f = up.files,
            i = f.length;

        while(i--){
            up.removeFile(f[i]);
        }

        this.store.removeAll();
        this.checkActions();
    },

    destroy: function(){
        if(this.uploader){
            this.uploader.destroy();
        }

        this.callParent();
    }
});